<?php

namespace app\controllers;

use app\components\Email;
use app\components\EmailMarket;
use app\components\msgcenter\MsgCenter;
use Ares333\Curl\Curl;
use Ares333\Curl\Toolkit;
use Yii;
use app\base\Controller;
//use app\modules\admin\crontab\components\mq\MqComponent;
use app\components\mq\MqComponent;
use app\models\Template;
use yii\db\Exception;
use yii\helpers\Json;

class TestController extends Controller
{
    public $enableCsrfValidation = false; //

    protected $curlTimes = 0;
    
    /**
     * 建表相关
     */
    public function actionCreateTable()
    {
        set_time_limit(0);
        $sites = Yii::$app->params['sites']['marketing_email']['web_index'];
        foreach($sites as $site) {
            for ($i=0;$i<100;$i++) {
                $tableName = "mail_sendlist_{$site}_{$i}";
                $tableSql = "
                CREATE TABLE `{$tableName}` (
                    `id` int(11) NOT NULL AUTO_INCREMENT,
                    `group_id` int(11) NOT NULL DEFAULT '0' COMMENT '分组id',  
                    `channel_id` tinyint(3) DEFAULT '0' COMMENT '通道id值',
                    `user_id` int(11) DEFAULT '0' COMMENT '用户id（edm用户表id）',
                    `site_user_id` int(11) DEFAULT '0' COMMENT '网站用户id',
                    `template_pk` int(11) unsigned DEFAULT '0' COMMENT '模板主键',
                    `firstname` varchar(100) DEFAULT NULL COMMENT '姓名',
                    `lastname` varchar(100) DEFAULT NULL COMMENT '姓',
                    `email` varchar(90) NOT NULL DEFAULT '' COMMENT '邮箱',
                    `add_date` int(10) DEFAULT NULL COMMENT '加入时间',
                    `send_hour` smallint(6) DEFAULT '0' COMMENT ' 发送时间',
                    `send_day` smallint(6) DEFAULT '1' COMMENT ' 发送时间 周几',
                    `email_type` smallint(6) DEFAULT '0' COMMENT '邮箱服务商',
                    `cart_goods_custom_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '定制在goods_data表中对应的id值',
                    PRIMARY KEY (`id`),
                    KEY `group` (`group_id`),
                    KEY `email` (`email`)
                ) ENGINE=INNODB  DEFAULT CHARSET=utf8 COMMENT='用户标签队列详情'
                ";
                Yii::$app->db->createCommand($tableSql)->execute();
                echo  $tableName . "创建完毕<br>";
            }
        }
        echo '表创建完毕<br>';
    }
    
    /*
     * 创建统计表结构
     */
    public function actionCreateStaticTables()
    {
        $sites = Yii::$app->params['sites']['marketing_email']['web_index'];
        foreach($sites as $site) {
            $tableSql = "
            CREATE TABLE if not exists `email_{$site}_open_data` (
                `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键id',
                `group_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '发送分组id',
                `sendlist_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT 'sendlist表id',
                `site_user_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '网站user_id',
                `user_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '用户id',
                `open_teminal` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '设备类型 0：other 1：ios 2：android 3：pc',
                `email_type` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '邮件服务商',
                `open_count` mediumint(8) unsigned NOT NULL DEFAULT '0' COMMENT '用户打开邮件次数',
                `open_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '打开时间',
                `is_sync` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '是否同步过 1：已同步 0：未同步',
                PRIMARY KEY (`id`),
                UNIQUE KEY `group_id_sendlist_idx` (`group_id`,`sendlist_id`) USING BTREE,
                KEY `open_teminal` (`open_teminal`) USING BTREE,
                KEY `email_type` (`email_type`) USING BTREE,
                KEY `is_sync` (`is_sync`) USING BTREE
              ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='打开明细数据表';
              CREATE TABLE if not exists `email_{$site}_send_success_fail_data` (
                `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键id',
                `group_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '发送分组id',
                `email` varchar(90) NOT NULL DEFAULT '' COMMENT '加密后的邮箱',
                `channel_id` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '通道id值',
                `status` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '发送状态 1：成功 0：失败',
                PRIMARY KEY (`id`),
                UNIQUE KEY `group_id_email_idx` (`group_id`,`email`) USING BTREE,
                KEY `status` (`status`)
              ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='通道式返回发送失败成功记录表';
            ";
              
//            var_dump($tableSql);exit;  
            Yii::$app->db->createCommand($tableSql)->execute();
            echo  $site . "站点表创建完毕<br>";
              
        }
        echo '表创建完毕<br>';
    }
    
    /**
     * @return array|bool|false|null|string
     * @throws Exception
     */
    public static function actionGetTemplate()
    {
        $siteId = Yii::$app->request->get('site_id');
        $uuqid = Yii::$app->request->get('uuqid');
        $lang = Yii::$app->request->get('lang');
        if(!$lang) {
            return null;
        }

//        $item = $sysRedisObj->hget(self::$cache_key_cur_new,strtolower($uuqid.'_'.$lang));
        //从文件缓存中读取模板数据
        $path = Yii::getAlias('@runtime/sys_template_cache/'.$siteId.'/'.$uuqid);
        $cacheFile = $path.'/'.$lang;
        if(is_file($cacheFile)){
            $item = file_get_contents($cacheFile);
            if($item) {
                var_dump($item);
                exit();
                $item = Json::decode($item);
                return $item;
            }
        }

        // 查询相应的模版数据放入缓存中
        $get_template_sql = "select * from template_new t join template_lang l on t.id = l.template_id where t.uuqid = '{$uuqid}' and t.is_delete = 0 and t.site_id= {$siteId} and l.lang='{$lang}' and l.is_enable = 1";
        $cur_template_data_arr = Yii::$app->db->createCommand($get_template_sql)->queryOne();
        if ($cur_template_data_arr) {
//            $sysRedisObj->hset(self::$cache_key_cur_new,strtolower($uuqid.'_'.$lang),Json::encode($cur_template_data_arr));
            //写入文件缓存
            if(!is_dir($path)){
                mkdir($path,0777,true);
            }
            file_put_contents($cacheFile,Json::encode($cur_template_data_arr));
            var_dump(Json::encode($cur_template_data_arr));
            exit();
            return $cur_template_data_arr;
        } else {
            return null;
        }
    }

    /**
     * 删除文件缓存，使用服务器IP直接连服务器删除缓存文件
     */
    public function actionDelFileCache()
    {
        $siteId = Yii::$app->request->get('site_id');
        $uuqid = Yii::$app->request->get('uuqid');
        $lang = Yii::$app->request->get('lang');
        $toolkit = new Toolkit();
        $curl = $toolkit->getCurl();
        $curl->onInfo = null;
        //直接连服务器的 IP，删除所有服务器上面的缓存文件
        $serveIps = Yii::$app->params['serve_ip'];
        foreach ($serveIps as $serveIp) {
            $curl->add(
                array(
                    'opt' => array(
                        CURLOPT_URL => 'http://'.$serveIp.':86/test/del-template-cache?site_id='.$siteId.'&uuqid='.$uuqid.'&lang='.$lang,
                    )
                )
            );
        }
        $curl->start();
    }

    /**
     * 调用模型里面的方法删除文件缓存
     */
    public function actionDelFileCacheFromModel()
    {
        $siteId = Yii::$app->request->get('site_id');
        $uuqid = Yii::$app->request->get('uuqid');
        $lang = Yii::$app->request->get('lang');
        $templateModel = new Template();
        $templateModel->delFileCache($siteId,$uuqid,$lang);
    }

    /**
     * 删除缓存文件，只会删除请求所有服务吕dk
     */
    public function actionDelTemplateCache()
    {
        $siteId = Yii::$app->request->get('site_id');
        $uuqid = Yii::$app->request->get('uuqid');
        $lang = Yii::$app->request->get('lang');
        $cacheDir = Yii::getAlias('@runtime/sys_template_cache');
        //如果删除指定模板的指定语言版本
        if($siteId && $uuqid && $lang){
            unlink($cacheDir.'/'.$siteId.'/'.$uuqid.'/'.$lang);
            return;
        }
        //如果没有指定语言版本，则删除该模板的所有语言版本
        if($siteId && $uuqid){
            $path = $cacheDir.'/'.$siteId.'/'.$uuqid;
            //exec(sprintf("rm -rf %s", escapeshellarg($path)));
            $this->rrmdir($path);
            return;
        }
        //如果只提供了站点ID，则删除该站点所有的模板缓存
        if($siteId){
            $path = $cacheDir.'/'.$siteId;
            //exec(sprintf("rm -rf %s", escapeshellarg($path)));
            $this->rrmdir($path);
        }
        return;
    }

    /**
     * 递归删除目录，先写在这里，后面再挪到公共的里面去
     * @param string $src 路径
     */
    private function rrmdir($src) {
        $dir = opendir($src);
        while(false !== ( $file = readdir($dir)) ) {
            if (( $file != '.' ) && ( $file != '..' )) {
                $full = $src . '/' . $file;
                if ( is_dir($full) ) {
                    $this->rrmdir($full);
                } else {
                    unlink($full);
                }
            }
        }
        closedir($dir);
        rmdir($src);
    }

    public function actionSql()
    {
        exit();
        $sql = "delete from user_gearbest_goods_data where user_email_type = 14 and from_unixtime(create_time,'%Y-%m-%d') = '2018-08-27'";
        Yii::$app->db->createCommand($sql)->execute();
        $sql = "update emp_gearbest_email_browse set is_deal = 0,state = 0 where action_date = '2018-08-25'";
        Yii::$app->db->createCommand($sql)->execute();
    }

    public function actionSql2()
    {
        exit();
        $sql = "update emp_gearbest_email_browse set is_deal = 1,state = 1 where action_date = '2018-08-25'";
        Yii::$app->db->createCommand($sql)->execute();
    }

    public function actionSql3()
    {
        exit();
        $sql = "update user_gearbest_goods_data set create_time = '1535353881' where user_email_type = 14 and from_unixtime(create_time,'%Y-%m-%d') = '2018-08-27'";
        Yii::$app->db->createCommand($sql)->execute();
    }

    public function actionMulti()
    {
        $toolkit = new Toolkit();
        $curl = $toolkit->getCurl();
        $curl->onInfo = null;
        $this->onSuccess($curl);
        $curl->start();
    }

    /**
     * @param Curl $curl
     */
    public function onSuccess($curl)
    {
        $this->curlTimes++;
        echo $this->curlTimes . "\n";
        if ($this->curlTimes >= 30) {
            return;
        }
        $curl->add(
            [
                'opt' => [
                    CURLOPT_URL => 'http://ems.appinthestore.com/crontab/premium-price-data-deal/put-premium-goods-to-mq?module_name=marketing_email&site=gearbest'
                ]
            ],
            function ($r) use ($curl) {
                $this->onSuccess($curl);
            }
        );
    }

    /**
     *  $rtx           ֧�ֶ�rtx
     *  $From_rtx      ������rtx
     *  $sitename       ��������
     *  $mail_subject   ����
     *  $rtx_body      ����
     */
    public function execRtx($rtx, $rtx_subject, $rtx_body)
    {
        if (is_array($rtx)) $rtx = implode(',', $rtx);
        if (strlen($rtx_body) > 200) $rtx_body = mb_substr($rtx_body, -200, 200, "utf-8");
        $rtx_subject = iconv("UTF-8", "GBK", $rtx_subject);
        $rtx_body = iconv("UTF-8", "GBK", $rtx_body);

        $url = "http://58.251.136.63:1010/api_wu.php";
        $post_data = array(
            "data" => "c695ab0ac9e43afc6f1ce8b724e09bf0a0bwuc" . $rtx_subject . "a0bwuc" . $rtx . "a0bwuc" . $rtx_body,
        );
        if (in_array($rtx, array(9777, 12375, 12696, 8811, 12611, 13603, 2555, 9640, 12975, 14619, 13626, 12804, 17160, 7129)) || strpos($rtx, ',')) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            $output = curl_exec($ch);
            curl_close($ch);
        }
    }

    public function actionIndex()
    {
        set_time_limit(0);

        header("Cache-Control: no-cache");
        header("Pragma: no-cache");
        $url = Yii::$app->request->getHostInfo();
        $php_error_test = [
            'error' => $url . '/test/test-php-error?site=sys_email',
            'mysql' => $url . '/test/test-sql-error?site=sys_email',

        ];


        foreach ($php_error_test as $url) {

            echo $url . '<br>';
            $result = $this->visitUrl($url);  // $result['info'=>[], 'contents'=>$contents]
            var_dump($result);
            echo '<hr>';
        }
    }

    public function actionEs()
    {
        $filters = [
            [
                'field' => 'lastOpen',
                'type' => 'range',
                'values' => [1516691078, 1529737478],
            ],
        ];
        $sorts = [
            [
                'field' => 'userId',
                'order' => 'desc',
            ]
        ];

        $where = [
            'filters' => $filters,
            'sorts' => $sorts
            //'aggregations' => $aggregations,
        ];
        $response = Yii::$app->es->search($where, 49, 2000);
        var_dump($response);
    }

    public function actionTestEmail()
    {
        $emailArr = [
            'etmXFbm8d1Wdx3AXcJXUEHuRYK2k97teX920FNieb227xcp0ct2bhyfLMBDuUUvLM0j3kvMjAxOCAxODozNToyMw==',
            'NtzXUbw8N1jdg32XMJzUkH0RQKHkF7xeL9m0NNveb2V79ch0Ytmb9ysLaBXuNUoLX0z3A2LzExLzIwMTggMTU6MjU6NDg=',
            'ctmX9bz8Z1Wdd3hXbJDUAH2RMKDkl7AeZ9201Nhea2W7wcu0Yt2b9ytLXB2uFUiLb023xpc2hfMDUvMjkvMjAxOCAxODozNDowMA==',
            'btGXlbq8a1WdV3vXbJzUEH5ROKTkV7AeZ9201Nhea2W7wcu0Yt2b9yuLXB2uFUiLb023xpc2hfMDUvMjkvMjAxOCAxODozMToyOQ==',
        ];
        $emailMarket = new \app\components\EmailMarket();
        foreach ($emailArr as $emailVal) {
            $email = $emailMarket->transferDecryption($emailVal);
            var_dump($email);
            echo '<br>';
        }
    }

    public function actionTestGbToken()
    {
        $postArr = [
            'header' => [
                'service' => 'com.globalegrow.mmember.spi.inter.IMemCommonInnerService',
                'method' => 'validToken',
                'domain' => '',
                'version' => '1.0.0',
                'tokenId' => '48528414c5e7aa417c4a58d6fcd64ab9',
            ],
            'body' => [
                'siteCode' => 'GB',
                'token' => '57beed2769b8492fa1323feacca31c56',
            ],
        ];
        $item['url'] = 'http://10.40.2.106:2087/gateway/';
        $item['options'][CURLOPT_POST] = 1;
        $item['options'][CURLOPT_POSTFIELDS] = json_encode($postArr);
        $item['options'][CURLOPT_HTTPHEADER] = array('Content-Type:application/json');

        $item['options'][CURLOPT_RETURNTRANSFER] = 1;
        $item['options'][CURLOPT_TIMEOUT] = 300;
        $result = yii::$app->curl->execute($item);
        var_dump($result);
        var_dump(json_decode($result, true));
    }

    public function actionTestPhpError()
    {

        set_time_limit(0);
        header("Cache-Control: no-cache");
        header("Pragma: no-cache");
        // ����һ�������ڵĺ���, ���� error �������
        WTF();
    }

    public function actionTestSqlError()
    {
        global $config;
        set_time_limit(0);
        header("Cache-Control: no-cache");
        header("Pragma: no-cache");

        // �����SQL�﷨����
        $sql = "SELECT * from test_mail_data_tables";
        $db = isset($config['components']['db']) ? 'db' : 'adminDb';
        $returnData = Yii::$app->$db->createCommand($sql)->queryOne();

        var_dump($returnData);

    }

    public function visitUrl($url)
    {
        if (!$url) return false;

        $ssl = substr($url, 0, 8) == "https://" ? TRUE : FALSE;


        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        //curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        if ($ssl) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        }

        $response_contents = curl_exec($ch);
        //$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $response_Info = curl_getinfo($ch);
        curl_close($ch);
        return ['info' => $response_Info, 'contents' => $response_contents];
    }


    /**
     * �����������
     */
    public function actionAddMail($uuqid = '', $email = null, $userId = null)
    {

        // $dataMailArr = array(
        // // �����ɹ�
        // 'create_order' => array(
        // 'uuqid' => 'create-order',
        // 'email' => '815227173@qq.com',
        // 'lang' => 'en',
        // 'data' => array(
        // 'password' => 'yumao815227173',
        // 'email' => '815227173@qq.com',
        // 'userId' => 234751,
        // ),

        // ),

        // //֧���ɹ����Ǹ��ѻ�Ա��
        // 'pay_order' => array(
        // 'uuqid' => 'pay-order',
        // 'email' => '815227173@qq.com',
        // 'lang' => 'en',
        // 'data' => array(
        // 'nickName' => 'yumao',
        // 'userId' => 234751,
        // '' =>
        // ),
        // ),

        // );
        //Yii::$app->params['sites']['sys_email']
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site_name = Yii::$app->request->$mothod('site_name');
        $email = Yii::$app->request->$mothod('email');
        $queue_name = Yii::$app->params['sites']['sys_email']['web_config'][$site_name]['new_user_queue_name'];
        //$data = $this->getSendMailData($uuqid, $email, $userId);


        // ��ģ��һ������


        $data = array(
            'uuqid' => 'GB_en-orderPayed',
//             'email' => 'fengxixian1@gmail.com',
//             'email' => 'jianyanhong@hotmail.com',
            'email' => 'liugang01@globalegrow.com',
            'pipelineCode' => 'GBUK',
            'lang'   => 'en',
            'data' => array(
                'password' => 'yumao815227173',
//                 'email' => 'fengxixian1@gmail.com',
//                 'email' => 'jianyanhong@hotmail.com',
                'email' => 'liugang01@globalegrow.com',
                'userId' => 234751,
            ),
        );



//        $data = array(
//            'siteCode' => 'GB',
//            'data' =>
//                array(
//                    'orders' =>
//                        array(
//                            0 =>
//                                array(
//                                    'orderSn' => '18053100992800288381',
//                                    'orderGoods' =>
//                                        array(
//                                            0 =>
//                                                array(
//                                                    'goodsTitle' => 'HNW - 018 USB Powered Bug Zapper Mosquito Killer Lamp ',
//                                                    'qty' => 1,
//                                                    'price' => 12.84,
//                                                    'goodsUrl' => 'https://www.gearbest.com/goods/pp_009687985868.html?wid=1433363',
//                                                    'warehouseCode' => '1433363',
//                                                    'goodsSn' => '264546401',
//                                                ),
//                                        ),
//                                ),
//                        ),
//                    'orderCurrencySymbol' => '��',
//                    'orderCurrency' => 'EUR',
//                    'domain' => 'https://www.gearbest.com',
//                    'nickName' => 'customer',
//                    'goodsList' =>
//                        array(
//                            0 =>
//                                array(
//                                    'goodsStatus' => 2,
//                                    'agvRate' => 4.7999999999999998,
//                                    'goodsWebSku' => '009202317157',
//                                    'goodsImage' => 'http://gloimg.gbtcdn.com/soa/gb/pdm-product-pic/Electronic/2017/10/24/goods-img/1525895705755710576.jpg',
//                                    'displayPrice' => '$407.2',
//                                    'discount' => 0,
//                                    'goodsSn' => '197762312',
//                                    'urlTitle' => '/cell-phones/pp_1029979.html',
//                                    'goodsUrl' => 'https://www.gearbest.com/goods/pp_009202317157.html?wid=1101231',
//                                    'wareCode' => '1101231',
//                                    'shopPrice' => 407.19999999999999,
//                                    'reviewCount' => 1062,
//                                    'favoriteCount' => 4703,
//                                    'youtube' => '',
//                                    'goodsTitle' => 'Xiaomi Mi Note 2 4G Phablet International Version',
//                                    'subTitle' => 'MIUI 8 or Above 5.7 inch Snapdragon 821',
//                                    'shopCode' => '355',
//                                    'catId' => 11293,
//                                ),
//                            1 =>
//                                array(
//                                    'goodsStatus' => 2,
//                                    'agvRate' => 4.7999999999999998,
//                                    'goodsWebSku' => '009566527964',
//                                    'goodsImage' => 'http://gloimg.gbtcdn.com/gb/pdm-product-pic/Electronic/2017/10/10/goods-img/1510288967451748341.jpg',
//                                    'displayPrice' => '$4.59',
//                                    'discount' => 27,
//                                    'goodsSn' => '207227804',
//                                    'urlTitle' => '/earbud-headphones/pp_603274.html',
//                                    'goodsUrl' => 'https://www.gearbest.com/goods/pp_009566527964.html?wid=1433363',
//                                    'wareCode' => '1433363',
//                                    'shopPrice' => 6.29,
//                                    'reviewCount' => 8073,
//                                    'favoriteCount' => 30241,
//                                    'youtube' => 'https://youtu.be/rW0cUNYsi6g',
//                                    'goodsTitle' => 'Original Xiaomi Piston In Ear Earphones Fresh Version',
//                                    'subTitle' => 'Built-in Mic / On-cord Control / Updated Damping Balance System',
//                                    'shopCode' => '348',
//                                    'catId' => 11241,
//                                ),
//                            2 =>
//                                array(
//                                    'goodsStatus' => 2,
//                                    'agvRate' => 4.5999999999999996,
//                                    'goodsWebSku' => '009892693294',
//                                    'goodsImage' => 'http://gloimg.gbtcdn.com/gb/pdm-product-pic/Electronic/2017/12/23/goods-img/1515352872440242277.jpg',
//                                    'displayPrice' => '$36.99',
//                                    'discount' => 19,
//                                    'goodsSn' => '249884903',
//                                    'urlTitle' => '/tv-box/pp_1509684.html',
//                                    'goodsUrl' => 'https://www.gearbest.com/goods/pp_009892693294.html?wid=1433363',
//                                    'wareCode' => '1433363',
//                                    'shopPrice' => 45.68,
//                                    'reviewCount' => 149,
//                                    'favoriteCount' => 2315,
//                                    'youtube' => 'https://youtu.be/dCUCjH9g6xk',
//                                    'goodsTitle' => 'Tanix TX3 Max TV Box',
//                                    'subTitle' => 'Amlogic S905W / Android 7.1 with New ALICE UX / 2GB RAM + 16GB ROM / 2.4GHz Wi-Fi / 4K / 100Mbps LAN / BT4.1',
//                                    'shopCode' => '348',
//                                    'catId' => 12313,
//                                ),
//                        ),
//                    'parentOrderSn' => '18053100992800288381',
//                    'email' => $email,
//                ),
//            'pipelineCode' => 'GB',
//            'lang' => 'en',
//            'uuqid' => 'GB-GB-en-orderCancel',
//            'email' => $email,
//        );
        \Yii::$app->mq->send(
            $queue_name,
            $data
        );
        var_dump($data);
    }

    /**
     * ��������
     *
     * @param string $uuqid
     * @param string $email
     * @param string $userId
     * @return array
     * @throws UserException
     */
    protected function getSendMailData($uuqid, $email, $userId)
    {
        $userId = $userId ?: rand(1, 1000000);
        //$email = $email ?: 'mashanling@globalegrow.com';
        $email = $email ?: 'yumao@globalegrow.com';
        switch ($uuqid) {
            case Template::REGISTER:
                $data = [
                    'password' => app()->helper->str->random(8),
                    'email' => $email,
                    'userId' => $userId,
                ];
                break;
            case Template::FORGET_PASSWORD:
            case Template::DROP_SHIPPING:
                $data = [
                    'nickName' => app()->helper->str->random(8),
                    'userId' => $userId,
                ];
                break;
            case Template::VALIDATE_EMAIL:
                $data = [
                    'userId' => $userId,
                ];
                break;
            case Template::RESET_PASSWORD:
                $data = [
                    'nickName' => app()->helper->str->random(8),
                    'userId' => $userId,
                    'newPassword' => app()->helper->str->random(8),
                ];
                break;
            case Template::ARRIVAL_NOTICE:
                $data = [
                    'nickName' => app()->helper->str->random(8),
                    'userId' => $userId,
                    'webGoodSn' => app()->helper->str->random(8),
                    'goodTitle' => app()->helper->str->random(50),
                    'imageUrl' => app()->helper->str->random(50),
                    'subTime' => time(),
                ];
                break;
            case Template::SUBSCRIBE:
                $data = [
                    'coupon' => app()->helper->str->random(8),
                    'userId' => $userId,
                    'password' => app()->request->get('password'),
                    'couponEndTime' => time(),
                ];
                break;
            case Template::CANCEL_ORDER:
                $data = [
                    'nickName' => app()->helper->str->random(8),
                    'orderSns' => [
                        app()->helper->str->random(8),
                        app()->helper->str->random(8),
                        app()->helper->str->random(8)
                    ]
                ];
                break;
            case Template::PAY_ORDER:
                $data = [
                    'nickName' => app()->helper->str->random(8),
                    'orderSns' => [
                        [
                            'url' => 'www.baidu.com',
                            'orderSn' => app()->helper->str->random(8)
                        ],
                        [
                            'url' => 'www.qq.com',
                            'orderSn' => app()->helper->str->random(8)
                        ],
                        [
                            'url' => 'www.163.com',
                            'orderSn' => app()->helper->str->random(8)
                        ],
                    ],
                    'orderAddress' => [
                        'firstName' => 'yu',
                        'lastName' => 'mao',
                        'addressLine1' => 'addressLine1',
                        'city' => 'shenzhen',
                        'province' => 'guangdong',
                        'postalCode' => '133',
                        'phone' => 137,
                    ],
                ];
                break;
            case Template::CREATE_ORDER:
            case Template::OMS_EDIT_ORDER:
                $data = [
                    'nickName' => app()->helper->str->random(8),
                    'orderAddress' => [
                        'addressLine1' => '12',
                        'city' => 'ss',
                        'country' => 'United States',
                        'firstName' => 'ddd',
                        'lastName' => 'ff',
                        'phone' => '13400001001',
                        'postalCode' => '11312424',
                        'province' => 'California'
                    ],
                    'orderAmountInfo' => [
                        'couponDeductAmount' => 9,
                        'currencySymbol' => '$',
                        'discountAmount' => 1,
                        'goodsAmount' => 20.81,
                        'insuranceAmount' => 3.08,
                        'integralDeductAmount' => 2,
                        'orderAmount' => 25.06,
                        'payDeductAmount' => 3,
                        'shippingAmount' => 1.17
                    ],
                    'orderInfos' => [
                        $order = [
                            'orderGoods' => [
                                [
                                    'currencySymbol' => '$',
                                    'goodsAttr' => '����Ь�ӳ��� =>One Size,Flounce =>Navy',
                                    'goodsSn' => 'YM2508303',
                                    'goodsTitle' => 'Korean Shawl Collar Solid Color',
                                    'price' => 20.81,
                                    'qty' => 1,
                                    'subTotal' => 20.81,
                                    'webGoodsSn' => 'd11wsoftg03 '
                                ],
                                [
                                    'currencySymbol' => '$',
                                    'goodsAttr' => '����Ь�ӳ��� =>One Size,Flounce =>Navy',
                                    'goodsSn' => 'YM2508303',
                                    'goodsTitle' => 'Korean Shawl Collar Solid Color',
                                    'price' => 20.81,
                                    'qty' => 1,
                                    'subTotal' => 20.81,
                                    'webGoodsSn' => 'd11wsoftg03 '
                                ]
                            ],
                            'orderSn' => '17030101123219544920',
                            'shippingName' => 'USRAMJH '
                        ],
                        $order
                    ],
                ];
                break;
            case Template::PARITY:
                $data = [
                    'nickName' => app()->helper->str->random(8),
                    'content' => app()->request->get('content', app()->helper->str->random(200)),
                    'goods' => [
                        'title' => app()->helper->str->random(8),
                        'price' => rand(1, 3),
                        'url' => 'http://www.trendsgal.com/p/wholesale-product-1704184.html',
                        'imgUrl' => 'http://gloimg.trendsgal.com/soa/tg/pdm-product-pic/Clothing/2016/11/04/goods-img/1487192852148216581.jpg',
                    ],
                ];
                break;
            case Template::VIP_RENEWAL:
                $data = [
                    'userId' => $userId,
                ];
                break;
            case Template::REFUND:
                $data = [
                    'userId' => $userId,
                    'orderSns' => [
                        '17011901160810449043',
                        '17022301121614451016',
                    ],
                    'payTypes' => [
                        'PP',
                        'GC'
                    ],
                    'refundDetail' => [
                        [
                            'refundTypeCode' => 'PP',
                            'currencyCode' => 'USD',
                            'currencyMoney' => 13.56,
                            'currencySymbol' => '$',
                            'money' => 13.56,
                            'transactionId' => 'liubing-test-123'
                        ],
                        [
                            'refundTypeCode' => 'GC',
                            'currencyCode' => 'USD',
                            'currencyMoney' => 13.56,
                            'currencySymbol' => '$',
                            'money' => 13.56,
                            'transactionId' => 'liubing-test-123'
                        ]
                    ],
                ];
                break;
            case Template::SHIPPED:
                $data = [
                    'userId' => $userId,
                    'expressPackage' => [
                        'deliveryTime' => 1484644337,
                        'imgUrl' => 'http://track.gfstatic.com/WMS_SortingPhoto/011/1702/d082aea0588716c30a848b4cbe648d1e.jpg',
                        'logisticsCode' => 'CNDHL',
                        'logisticsName' => 'DHL',
                        'logisticsSn' => 'HK17021101108',
                        'orderGoods' => [
                            [
                                'currencySymbol' => null,
                                'goodsAttr' => ',��ɫ:Off-White',
                                'goodsSn' => '136098504',
                                'goodsTitle' => 'Fashion Style Crocodile Print and Metallic Design Tote Bag',
                                'price' => null,
                                'qty' => 3,
                                'subTotal' => null,
                                'webGoodsSn' => 'uus96xatg04'
                            ],
                            [
                                'currencySymbol' => null,
                                'goodsAttr' => '��ָӢ���ߴ�:M,��ɫ:Leopard',
                                'goodsSn' => 'YM7661303',
                                'goodsTitle' => 'Low-Cut V-Neck Leopard Print Long Sleeves Alluring Women Bodycon Dress',
                                'price' => null,
                                'qty' => 5,
                                'subTotal' => null,
                                'webGoodsSn' => 'lj7un82tg03'
                            ]
                        ],
                    ],
                    'orderSn' => '17021101108011194502',
                    'shippingName' => 'USUPSHQ',
                    'email' => 'cheng@qq.com',
                ];
                break;
            case Template::PAY_VIP:
                $data = [
                    'userId' => $userId,
                    'goodsTitle' => app()->helper->str->random(8),
                ];
                break;
            case Template::REMINDER_PAY_ORDER:
                $data = [
                    'userId' => $userId,
                    'orders' => [
                        [
                            'orderSn' => app()->helper->str->random(8),
                            'currencySymbol' => 'USD',
                            'orderCurrencyAmount' => 13.56,
                            'createdTime' => time(),
                        ],
                        [
                            'orderSn' => app()->helper->str->random(8),
                            'currencySymbol' => 'USD',
                            'orderCurrencyAmount' => 18.02,
                            'createdTime' => time(),
                        ],
                    ]
                ];
                break;
            default:
                throw new UserException('uuqid?');
        }

        return [
            'uuqid' => $uuqid,
            'email' => $email,
            'data' => $data
        ];
    }

    /**
     * ������ض��е�����
     */
    public function actionExpendMess()
    {
        MqComponent::expense();
    }

    /**
     * ������������
     */
    public function actionSendMail()
    {
        MqComponent::sendMail();
    }

    public function actionDecrytionMail()
    {
        $enMail = 'YF28h7lPbonyNuoXY2W3533uZiWI5qAgZT2jxKv0YGmXF8spZiW2d1ynb03gcpuY29t';
        $deMail = (new Email())->decryption($enMail);
        var_dump($deMail);
    }

}
